"use client";
import React from "react";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { zodResolver } from "@hookform/resolvers/zod";
import { Trash } from "lucide-react";
import { useParams, useNavigate } from "react-router-dom";
import { useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { AlertModal } from "../modal/alert-modal";
import { createTenant, updateTenant } from "@/api";
import { TenantI } from "@/types";

const formSchema = z.object({
  // id: z.string().optional(),
  id: z.string(),
  name: z.string().trim().min(3, { message: "中心名称至少3个字符" }),
  description: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
});

type FormValuesT = z.infer<typeof formSchema>;

interface FormPropsI {
  initialData: TenantI | undefined;
}

export const TenantForm: React.FC<FormPropsI> = ({ initialData }) => {
  const params = useParams();
  const navigate = useNavigate();
  // const { toast } = useToast();
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const title = initialData ? "编辑中心信息" : "创建中心信息";
  const description = initialData ? "" : "";
  const toastMessage = initialData ? "保存成功" : "创建成功";
  const action = initialData ? "保存" : "创建";

  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: initialData || {
      id: undefined,
      name: "",
      description: "",
    },
  });

  const onSubmit = async (data: FormValuesT) => {
    try {
      setLoading(true);
      if (initialData) {
        updateTenant(data).then((res) => {
          console.log(res);
        });
      } else {
        // const res = await axios.post(`/api/products/create-product`, data);
        // console.log("product", res);
      }
      // navigate(`/dashboard/products`);
      // toast({
      //   variant: "destructive",
      //   title: "Uh oh! Something went wrong.",
      //   description: "There was a problem with your request.",
      // });
    } catch (error: any) {
      // toast({
      //   variant: "destructive",
      //   title: "Uh oh! Something went wrong.",
      //   description: "There was a problem with your request.",
      // });
    } finally {
      setLoading(false);
    }
  };

  const onDelete = async () => {
    try {
      setLoading(true);
      //   await axios.delete(`/api/${params.storeId}/products/${params.productId}`);
      // navigate(`/${params.storeId}/products`);
    } catch (error: any) {
    } finally {
      setLoading(false);
      setOpen(false);
    }
  };

  React.useEffect(() => {
    form.reset(initialData);
  }, [initialData]);

  return (
    <>
      <AlertModal
        isOpen={open}
        onClose={() => setOpen(false)}
        onConfirm={onDelete}
        loading={loading}
      />
      <div className="flex items-center justify-between">
        <Heading title={title} description={description} />
        {initialData && (
          <Button
            disabled={loading}
            variant="destructive"
            size="sm"
            onClick={() => setOpen(true)}
          >
            <Trash className="h-4 w-4" />
          </Button>
        )}
      </div>
      <Separator />
      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="w-full space-y-8"
        >
          {/* <div className="gap-8 md:grid md:grid-cols-3"> */}
          <div className="flex flex-col gap-4">
            {initialData && initialData.id ? (
              <FormField
                control={form.control}
                name="id"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>ID</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="id"
                        {...field}
                        disabled={initialData && initialData.id ? true : false}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            ) : null}
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>中心名称</FormLabel>
                  <FormControl>
                    <Input
                      disabled={loading}
                      placeholder="Tenant name"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="description"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>描述</FormLabel>
                  <FormControl>
                    <Textarea
                      disabled={loading}
                      placeholder="Tenant description"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
          <Button disabled={loading} className="ml-auto" type="submit">
            {action}
          </Button>
        </form>
      </Form>
    </>
  );
};
